package com.zdxk.msgPush.stockMsg.read.service;

import com.alibaba.fastjson.JSONObject;
import com.zdxk.msgPush.common.config.RocketMqConfig;
import com.zdxk.msgPush.common.config.ServiceConfig;
import com.zdxk.msgPush.common.rocket.produce.RocketMqProducer;
import com.zdxk.msgPush.stockMsg.vo.StockTradeVo;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class StockDataReadService{

    public List<File> getStockDataFromFile(){
        List<File> fileList = new ArrayList<>();
        String path = ServiceConfig.getConf("stock.trade.dataPath");
        File file = new File(path);		//获取其file对象
        File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
        for(File f:fs){					//遍历File[]数组
            if(!f.isDirectory()) {        //若非目录(即文件)，则打印
                fileList.add(f);
            }
        }
        return fileList;
    }

    public void publishAllStockTradeByDate(Calendar calendar) throws IOException, InterruptedException, RemotingException, MQClientException, MQBrokerException {
        String text = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(calendar.getTime());
        List<File> fileList = getStockDataFromFile();
        for(File file : fileList){
            BufferedReader br = new BufferedReader(new FileReader(file));//读文件
            String rl = null;//临时的每行数据
            while ((rl = br.readLine()) != null) {
                if(rl.indexOf(dateStr) != -1){
                    text = rl;
                    break;
                }
            }
            if(text!=null){
                StockTradeVo tradeVo = tradeInfoStrToMap(text);
                Message msg = new Message(RocketMqConfig.getConf("rocketMq.topic"), tradeVo.getTsCode(),JSONObject.toJSONString(tradeVo).getBytes());
                RocketMqProducer.getProducer().send(msg);
            }
        }
    }

    public StockTradeVo tradeInfoStrToMap(String tradeInfoStr){
        String[] tradeArray = tradeInfoStr.split(";");
        return new StockTradeVo(tradeArray[0],
                tradeArray[1],
                Float.parseFloat(tradeArray[2]),
                Float.parseFloat(tradeArray[3]),
                Float.parseFloat(tradeArray[4]),
                Float.parseFloat(tradeArray[5]),
                Float.parseFloat(tradeArray[6]),
                Float.parseFloat(tradeArray[7]),
                Float.parseFloat(tradeArray[8]),
                Float.parseFloat(tradeArray[9]),
                Float.parseFloat(tradeArray[10])
        );
    }
}
